package ru.aslanov.schedule.server;

import ru.aslanov.schedule.model.Document;
import ru.aslanov.schedule.model.Schedule;

import javax.jdo.PersistenceManager;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created by IntelliJ IDEA.
 * Created: Feb 17, 2010 12:31:05 PM
 *
 * @author Sergey Aslanov
 */
public class DownloadDocumentServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        final String key = request.getParameter("key");
        String scheduleKey = request.getParameter("scheduleKey");
        final PersistenceManager pm = PMF.getThreadLocalPersistenceManager();
        //try {
            final Document document;
            if (key == null && scheduleKey != null) {
                final Schedule schedule = pm.getObjectById(Schedule.class, scheduleKey);
                document = schedule.getPublishedDocument();
                if (document == null) {
                    throw new ServletException("Schedule is not published: '" + scheduleKey + "'");
                }
            } else {
                document = pm.getObjectById(Document.class, key);
            }            
            response.setContentType(document.getType());
            response.getOutputStream().write(document.getData().getBytes());
        //} finally {
        //    pm.close();
        //}

    }
}
